/*
 * Copyright 2016 Elvis Hew
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.elvishew.xlogsample;

import com.elvishew.xlogsample.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventPublishInfo;
import ohos.hiviewdfx.HiLog;

public class MainAbility extends Ability {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == Constants.PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                HiLog.info(Constants.LABEL_LOG, "---permissions:" + permissions[0] + "---grantResults:" + grantResults[0]);
                if (permissions[i].equals("ohos.permission.WRITE_USER_STORAGE")) {
                    publishCommon(grantResults[i]);
                }
            }
        }
    }

    /**
     * 发布权限回调结果
     *
     * @param grantResult
     */
    private void publishCommon(int grantResult) {
        try {
            HiLog.info(Constants.LABEL_LOG, "ability publishCommon");
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withAction(Constants.COMMON_EVENT_ACTION).build();
            intent.setOperation(operation);
            CommonEventData commonEventData = new CommonEventData(intent);
            if (grantResult == 0) {
                commonEventData.setData(Constants.GRANT_PERMISSION);
            } else {
                commonEventData.setData(Constants.NO_GRANT_PERMISSION);
            }

            CommonEventPublishInfo commonEventPublishInfo = new CommonEventPublishInfo();
            commonEventPublishInfo.setOrdered(true);
            CommonEventManager.publishCommonEvent(commonEventData, commonEventPublishInfo);
        } catch (Exception e) {
            HiLog.error(Constants.LABEL_LOG,e.toString());
        }
    }
}
